// JWT token 工具函数
import { userStorage } from './storage'
import { refreshToken } from '@/api/auth'

// 获取token
export const getToken = () => {
  return userStorage.getToken()
}

// 设置token
export const setToken = (token) => {
  userStorage.setToken(token)
}

// 删除token
export const removeToken = () => {
  userStorage.removeToken()
}

// 退出登录
export const logout = () => {
  userStorage.removeToken()
  userStorage.removeRefreshToken()
  userStorage.removeUserInfo() 
  // 不清除记住我相关信息（用户名、密码、记住我勾选状态）
  
  // 清除可能存在的旧token
  localStorage.removeItem('token')
  sessionStorage.removeItem('token')
}

/**
 * 解析JWT，返回payload对象
 */
const parseJwt = (token) => {
  if (!token) return null
  try {
    const base64Url = token.split('.')[1]
    const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/')
    const jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
      return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
    }).join(''))
    return JSON.parse(jsonPayload)
  } catch (e) {
    return null
  }
}

/**
 * 检查token是否即将到期，到期则自动刷新
 * 返回Promise<boolean>，true为有效，false为无效
 */
export const checkAndRefreshToken = async () => {
  const token = getToken()
  if (!token) return false
  const payload = parseJwt(token)
  if (!payload || !payload.exp) return false
  const now = Math.floor(Date.now() / 1000)
  // 预留1分钟刷新
  if (payload.exp - now < 60) {
    const refresh = userStorage.getRefreshToken()
    if (!refresh) return false
    try {
      const res = await refreshToken({ refreshToken: refresh })
      if (res && res.data && res.data.accessToken) {
        setToken(res.data.accessToken)
        userStorage.setRefreshToken(res.data.refreshToken)
        return true
      }
    } catch (e) {
      return false
    }
  }
  return true
}

/**
 * 检查token是否有效
 * @returns {boolean} token是否有效
 */
export const isTokenValid = () => {
  const token = getToken()
  if (!token) return false
  const payload = parseJwt(token)
  if (!payload || !payload.exp) return false
  const now = Math.floor(Date.now() / 1000)
  return payload.exp > now
}

/**
 * 获取token的过期时间
 * @returns {number|null} 过期时间戳，如果无效返回null
 */
export const getTokenExpiration = () => {
  const token = getToken()
  if (!token) return null
  const payload = parseJwt(token)
  if (!payload || !payload.exp) return null
  return payload.exp * 1000 // 转换为毫秒
}

/**
 * 获取token中的用户信息
 * @returns {object|null} 用户信息对象，如果无效返回null
 */
export const getTokenUserInfo = () => {
  const token = getToken()
  if (!token) return null
  const payload = parseJwt(token)
  if (!payload) return null
  return {
    userId: payload.sub || payload.userId,
    username: payload.username,
    email: payload.email,
    roles: payload.roles || payload.role
  }
}
